package com.jindouyun.consumer.processor;

import com.jindouyun.common.annotations.JDYReference;
import com.jindouyun.consumer.client.ClientProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;

/**
 * @className: com.jindouyun.consumer.processor.JDYReferenceBeanPostProcessor
 * @description: 筋斗云依赖Bean的后处理器
 * @author: tong.li
 * @createTime: 2021/10/14 16:18
 * @copyright: Tongcheng-Elong Holdings Limited
 */
@Component
public class JDYReferenceBeanPostProcessor implements BeanPostProcessor {

    private final Logger log = LoggerFactory.getLogger(JDYReferenceBeanPostProcessor.class);

    @Resource
    private ClientProxy clientProxy;


    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // 查看bean字段中有没有对应的注解
        Field[] fields = bean.getClass().getDeclaredFields();
        for (Field field : fields) {
            // 判断字段是否有@JDYReference
            JDYReference annotation = field.getAnnotation(JDYReference.class);
            if (annotation == null) {
                continue;
            }
            Object proxy = clientProxy.proxyExecute(field.getType());
            // 通过反射进行赋值
            field.setAccessible(true);
            try {
                field.set(bean, proxy);
            } catch (IllegalAccessException e) {
                log.error(e.getMessage(),e);
            }
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }


}
